package me.shurufa.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.kaopiz.kprogresshud.KProgressHUD;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.model.Book;
import me.shurufa.model.TransfromResponse;
import me.shurufa.model.UploadResponse;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.NetworkConstants;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.Settings;
import me.shurufa.utils.Utils;
import me.shurufa.widget.crop.util.FileUtils;
import okhttp3.Request;

/**
 * CameraActivity 获取图片后跳转至此Activity
 *
 * @FileName: me.shurufa.activities.BitmapTransformActivity.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-18 13:31
 */
public class BitmapTransformActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    @Bind(R.id.left_text)
    TextView leftText;
    @Bind(R.id.right_image)
    ImageView rightImage;
    @Bind(R.id.right_text)
    TextView rightText;
    @Bind(R.id.tramsform_img)
    ImageView tramsformImg;


    @Bind(R.id.transform_btn)
    Button transformBtn;
    @Bind(R.id.transform_edit)
    EditText transformEdit;
    @Bind(R.id.save_and_send)
    RadioButton saveAndSend;
    @Bind(R.id.save_no_send)
    RadioButton saveNoSend;
    @Bind(R.id.tramsform_rg)
    RadioGroup tramsformRg;
    @Bind(R.id.transform_take_photo)
    TextView transformTakePhoto;
    @Bind(R.id.transform_save_digest)
    TextView transformSaveDigest;
    @Bind(R.id.note_layout)
    LinearLayout noteLayout;
    @Bind(R.id.note_text)
    TextView noteText;
//    @Bind(R.id.tramsform_save_img)
//    TextView tramsformSaveImg;

//    image path
    protected String mPath;
//    radio button check
    private boolean isSend=true;
    private KProgressHUD kProgressHUD;
    String note;
    private InputMethodManager imm;
    private long bookId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_bitmap_transform;
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        bookId = getIntent().getLongExtra(Constants.ARG_BOOK_ID,0L);
        configBitmap();
        initToolBar();
        initUI();
    }

    private void initToolBar() {
        rightText.setText(getString(R.string.mark_down));
        rightText.setVisibility(View.VISIBLE);
        titleTextView.setText(getString(R.string.make_digest));
        rightText.setOnClickListener(this);

    }

    private void initUI() {
        saveAndSend.setChecked(true);
        saveAndSend.setOnCheckedChangeListener(this);
        saveNoSend.setOnCheckedChangeListener(this);
        transformBtn.setOnClickListener(this);
        transformTakePhoto.setOnClickListener(this);
        transformSaveDigest.setOnClickListener(this);
        noteLayout.setVisibility(View.GONE);
//        tramsformSaveImg.setOnClickListener(this);

    }

    void configBitmap() {
        mPath = getIntent().getStringExtra(Constants.EXTRA_CAMERA_PHOTO);
        Bitmap bmp = BitmapFactory.decodeFile(mPath);
        tramsformImg.setImageBitmap(bmp);
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()){
            case R.id.transform_btn:
                uploadImg(mPath);
                break;
            case R.id.transform_take_photo:
                intent = new Intent(BitmapTransformActivity.this,CameraActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.transform_save_digest:
//                跳转设置书摘信息全部成功后返回该页 该页才能finish()
                if (checkDigest()) {
                    if (bookId==0L) {
                        intent = new Intent(BitmapTransformActivity.this, AddDigestActivity.class);
                        intent.putExtra(Constants.ARG_DIGEST_CONTENT, transformEdit.getText().toString().trim());
                        intent.putExtra(Constants.ARG_DIGEST_STATE, isSend);
                        if (!TextUtils.isEmpty(note))
                            intent.putExtra(Constants.ARG_DIGEST_NOTE, note);
                    }else {
                        intent = new Intent(BitmapTransformActivity.this,AddDigestMenuActivity.class);
                        Book book = new Book();
                        book.book_id = bookId;
                        intent.putExtra(Constants.ARG_DIGEST_CONTENT, transformEdit.getText().toString().trim());
                        intent.putExtra(Constants.ARG_DIGEST_STATE, isSend);
                        if (!TextUtils.isEmpty(note))
                            intent.putExtra(Constants.ARG_DIGEST_NOTE, note);
                        intent.putExtra(Constants.ARG_BOOK,book.toString());
                    }
                    startActivityForResult(intent, Constants.REQUEST_SKIP_BOOKCONIFG_CODE);
                }
                break;
//            case R.id.tramsform_save_img:
//                break;
//            case R.id.left_text:
//                intent = new Intent(Constants.ACTION_MAIN_SWITCH);
//                intent.putExtra(Constants.EXTRA_SWITCH_INDEX,1);
//                EventBus.getDefault().post(intent);
//                finish();
//                break;
            case R.id.right_text:
//                intent = new Intent(Constants.ACTION_MAIN_SWITCH);
//                intent.putExtra(Constants.EXTRA_SWITCH_INDEX,0);
//                EventBus.getDefault().post(intent);
//                finish();
                intent = new Intent(BitmapTransformActivity.this,WriteNoteActivity.class);
                if (!TextUtils.isEmpty(note))
                    intent.putExtra(Constants.ARG_DIGEST_NOTE,note);
                startActivityForResult(intent,Constants.REQUEST_NOTE_CODE);
                break;
        }
    }

    private boolean checkDigest() {
        String text = transformEdit.getText().toString().trim();
        if (TextUtils.isEmpty(text)){
            Utils.showToast(R.string.digest_content_not_be_empty);
            return false;
        }else if (text.length()<10){
            Utils.showToast(R.string.content_must_greater_than_10);
            return false;
        }else
            return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(transformEdit.getWindowToken(), 0);
        if (requestCode ==Constants.REQUEST_NOTE_CODE&&resultCode==RESULT_OK) {
            note = data.getStringExtra(Constants.ARG_DIGEST_NOTE);
            if (!TextUtils.isEmpty(note)) {
                noteLayout.setVisibility(View.VISIBLE);
                noteText.setText(note);
            } else {
                noteLayout.setVisibility(View.GONE);
                noteText.setText("");
            }
//            下方判断预留
        }else if (requestCode == Constants.REQUEST_SKIP_BOOKCONIFG_CODE&&requestCode==RESULT_OK)
            finish();
    }

    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (intent.getAction().equals(Constants.ACTION_ADD_DIGEST_COMPLETE))
            finish();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()){
            case R.id.save_and_send:
                if (isChecked)
                    isSend = true;
                else
                    isSend = false;
                break;
            case R.id.save_no_send:
                if (isChecked)
                    isSend = false;
                else
                    isSend = true;
        }
    }


    private void uploadImg(String path) {
        File file = new File(path);
        kProgressHUD = KProgressHUD.create(this);
        kProgressHUD.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel(getString(R.string.commit_pls_wait))
                .setCancellable(false)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();
        OkHttpUtils.post()//
                .addFile("image",file.getName(),file)
                .addParams("token",Global.currentUser.token)
                .url(NetworkConstants.READ_TEXT_FROM_IMAGE)
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void inProgress(float progress) {
                    }

                    @Override
                    public void onError(Request request, Exception e) {
                        Utils.showToast("提交失败0");
                        if (kProgressHUD != null) {
                            kProgressHUD.dismiss();
                            kProgressHUD = null;
                        }
                    }

                    @Override
                    public void onResponse(String s) {
                        doResult(s);
                    }
                });
    }

    private void doResult(String s) {
        if (!TextUtils.isEmpty(s)) {
            LogUtils.kLog().d(s);
        }
        TransfromResponse result = null;
        try{
            if (!TextUtils.isEmpty(s)){
                result = Global.getGson().fromJson(s,TransfromResponse.class);
            }else {
                result = null;
            }
            if (result != null && result.success) {
                if (result.data!=null&&!TextUtils.isEmpty(result.data.text.toString().trim())) {
                    transformEdit.setText(result.data.text.toString().trim());
                }else
                    Utils.showToast("未找到内容");
            } else {
                if (result!=null){
                    Utils.showToast(result.error.message);
                }else {
                    Utils.showToast("提交失败1");
                }
            }
        }catch (Exception e){}
        finally {
            if (kProgressHUD!=null){
                kProgressHUD.dismiss();
            }
        }
    }

    @Override
    protected void onDestroy() {
        File file = new File(mPath);
        if(file.exists()){
            FileUtils.deleteFile(file);
        }
        super.onDestroy();

    }
}
